package com.ll.wechat.user.activity;

import java.io.ByteArrayOutputStream;

import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smackx.vcardtemp.packet.VCard;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.ll.wechat.R;
import com.ll.wechat.base.activity.BaseActivity;
import com.ll.wechat.base.app.Constant;
import com.ll.wechat.base.app.User;
import com.ll.wechat.base.net.NetUtil;
import com.ll.wechat.base.utils.thread.ThreadPoolUtil;
import com.ll.wechat.base.utils.widget.MyToast;
import com.ll.wechat.user.widget.SexSelectDiaLog;

/**
 * 用户信息界面
 * 
 * @ClassName: UserInfoActivity
 * @author yeliangliang
 * @date 2015-8-10 下午1:28:03
 */
public class UserInfoActivity extends BaseActivity implements OnClickListener {

	private RelativeLayout rl_img_head;// 头像
	private RelativeLayout rl_small_name;// 昵称
	private RelativeLayout rl_sex;
	private TextView tv_smallNmae;// 昵称
	private TextView tv_passName;// 账号
	private SimpleDraweeView img_head;// 头像
	private TextView tv_sex;// 性别
	private SexSelectDiaLog diaLog;// 性别选择对话框
	private AbstractXMPPConnection connection;
	public final static int REQUEST_CODE_IMG = 1000;// 图片切割
	public final static int CODE_UPLOAD_IMG = 2000;// 图片上传
	public final static int CODE_SMALL_NAME = 3000;// 昵称修改
	private VCard vCard;// 信息对象

	@Override
	public void initView() {
		setContentView(R.layout.activity_userinfo);
		getActionBar().setDisplayShowHomeEnabled(false);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		setTitle("个人信息");
		// 寻址、监听
		findViewAndSetOnclick();
	}

	/**
	 * 寻址、监听
	 * 
	 * @author yeliangliang
	 * @date 2015-8-11 上午11:18:50
	 * @version V1.0
	 * @return void
	 */
	private void findViewAndSetOnclick() {
		rl_img_head = (RelativeLayout) findViewById(R.id.rl_img_head);
		rl_img_head.setOnClickListener(this);
		rl_small_name = (RelativeLayout) findViewById(R.id.rl_small_name);
		rl_small_name.setOnClickListener(this);
		tv_smallNmae = (TextView) findViewById(R.id.tv_small_name);
		tv_passName = (TextView) findViewById(R.id.tv_passName);
		img_head = (SimpleDraweeView) findViewById(R.id.img_head);
		rl_sex = (RelativeLayout) findViewById(R.id.rl_sex);
		rl_sex.setOnClickListener(this);
		tv_sex = (TextView) findViewById(R.id.tv_sex);
	}

	@Override
	public void initData() {
		connection = User.getInstance().getConnection();
		// 设置信息
		setTextInfo();
	}

	/**
	 * 设置用户信息显示出来
	 * 
	 * @author yeliangliang
	 * @date 2015-8-11 上午11:30:19
	 * @version V1.0
	 * @return void
	 */
	private void setTextInfo() {
		Runnable runnable = new Runnable() {

			@Override
			public void run() {
				VCard vCard2 = new VCard();
				try {
					vCard2.load(connection);
				} catch (Exception e) {
					handler.obtainMessage(Constant.REQUEST_FAILD).sendToTarget();
					e.printStackTrace();
				}
				handler.obtainMessage(Constant.REQUEST_SUCCESS, vCard2).sendToTarget();
			}
		};
		ThreadPoolUtil.insertTaskToCatchPool(runnable);
	}

	/**
	 * 款线程操作
	 */
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Constant.REQUEST_SUCCESS:// 用户信息请求成功
				vCard = (VCard) msg.obj;
				tv_passName.setText(User.getInstance().getUserInfo().getUserName());
				tv_smallNmae.setText(vCard.getNickName());
				if (vCard.getAvatar() != null && vCard.getAvatar().length != 0) {
					img_head.setImageBitmap(BitmapFactory.decodeByteArray(vCard.getAvatar(), 0,
							vCard.getAvatar().length));
				}
				tv_sex.setText(vCard.getEmailHome());
				break;

			default:
				break;
			}
			super.handleMessage(msg);
		}

	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
			finishActivity(UserInfoActivity.this);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:// actionbar返回按钮
			finishActivity(this);
			return true;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.rl_img_head:// 上传头像
			selectImg();
			break;
		case R.id.rl_small_name:// 修改昵称
			Bundle bundle = new Bundle();
			bundle.putString("name", tv_smallNmae.getText().toString());
			showActivityForResult(UserInfoActivity.this, ModifySmallNameActivity.class, bundle,
					CODE_SMALL_NAME);
			break;
		case R.id.rl_sex:// 修改性别
			modifySex();
			break;
		default:
			break;
		}
	}

	/**
	 * 修改性别
	 * 
	 * @author yeliangliang
	 * @date 2015-8-11 上午11:45:52
	 * @version V1.0
	 * @return void
	 */
	private void modifySex() {
		if (diaLog == null) {
			diaLog = new SexSelectDiaLog(this);
			View view = diaLog.getView();
			RelativeLayout rl_nan = (RelativeLayout) view.findViewById(R.id.rl_nan);
			RelativeLayout rl_nv = (RelativeLayout) view.findViewById(R.id.rl_nv);
			final ImageView img_nan = (ImageView) view.findViewById(R.id.img_nan);
			final ImageView img_nv = (ImageView) view.findViewById(R.id.img_nv);
			rl_nan.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					img_nan.setVisibility(View.VISIBLE);
					img_nv.setVisibility(View.GONE);
					if (connection == null) {
						diaLog.cancel();
						return;
					}
					VCard vCard3 = new VCard();
					vCard3.setEmailHome("男");
					try {
						vCard3.save(connection);
					} catch (Exception e) {
						diaLog.cancel();
						e.printStackTrace();
					}
					tv_sex.setText("男");
					diaLog.cancel();
				}
			});
			rl_nv.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					img_nv.setVisibility(View.VISIBLE);
					img_nan.setVisibility(View.GONE);
					if (connection == null) {
						diaLog.cancel();
						return;
					}
					VCard vCard4 = new VCard();
					try {
						vCard4.save(connection);
						vCard4.setEmailHome("女");
					} catch (Exception e) {
						diaLog.cancel();
						e.printStackTrace();
					}
					tv_sex.setText("女");
					diaLog.cancel();
				}
			});

		}
		if (!diaLog.isShowing()) {
			diaLog.show();
		}
	}

	/**
	 * 选择头像
	 * 
	 * @author yeliangliang
	 * @date 2015-8-10 下午3:15:49
	 * @version V1.0
	 * @return void
	 */
	private void selectImg() {
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(intent, REQUEST_CODE_IMG);
		//
		// VCard vCard = new VCard();
		// // vCard.setFirstName("kir");//姓
		// // vCard.setLastName("max");//名
		// // vCard.setEmailHome("foo@fee.bar");//邮箱
		// // vCard.setJabberId("jabber@id.org");//没猜到
		// // vCard.setOrganization("Jetbrains, s.r.o");//大概是公司的意思
		// vCard.setNickName("KIR");// 昵称
		// // vCard.setField("TITLE", "Mr");
		// vCard.setAddressFieldHome("STREET", "Some street");// 地址
		// // vCard.setAddressFieldWork("CTRY", "US");//公司地址
		// // vCard.setPhoneWork("FAX", "3443233");//电话
		// // 竟然没有设置性别这个方法。。。。 暂时使用邮箱来代替了
		// vCard.setEmailHome("foo@fee.bar");// 性别
		// // vCard.setAvatar();
		// try {
		// vCard.save(connection);
		// } catch (NoResponseException e) {
		// e.printStackTrace();
		// } catch (XMPPErrorException e) {
		// e.printStackTrace();
		// } catch (NotConnectedException e) {
		// e.printStackTrace();
		// }

	}

	// 回调
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {// 返回成功
			if (requestCode == REQUEST_CODE_IMG) {// 头像选择返回
				splitImg(data);// 切割图像
			} else if (requestCode == CODE_UPLOAD_IMG) {
				// 上传图像
				upLoadImg(data);
			} else if (requestCode == CODE_SMALL_NAME) {
				// 昵称修改
				if (data.getBooleanExtra("isSuccess", false)) {
					tv_smallNmae.setText(data.getStringExtra("name"));
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 上传头像
	 * 
	 * @param data
	 * @author yeliangliang
	 * @date 2015-8-10 下午5:01:54
	 * @version V1.0
	 * @return void
	 */
	private void upLoadImg(Intent data) {
		if (!NetUtil.isNetConnection()) {
			MyToast.showToast(UserInfoActivity.this, "网络断开连接");
			return;
		}
		Bitmap bmap = data.getParcelableExtra("data");
		VCard vCard = new VCard();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
		vCard.setAvatar(baos.toByteArray());
		try {
			vCard.save(connection);
		} catch (Exception e) {
			MyToast.showToast(UserInfoActivity.this, "上传失败");
			e.printStackTrace();
		}
		MyToast.showToast(UserInfoActivity.this, "上传成功");
	}

	/**
	 * 切割图片
	 * 
	 * @param data
	 * @author yeliangliang
	 * @date 2015-8-10 下午4:20:28
	 * @version V1.0
	 * @return void
	 */
	private void splitImg(Intent data) {
		Uri uri = data.getData();
		Intent intent = new Intent();
		intent.setAction("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");// mUri是已经选择的图片Uri
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);// 裁剪框比例
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 150);// 输出图片大小
		intent.putExtra("outputY", 150);
		intent.putExtra("return-data", true);
		this.startActivityForResult(intent, CODE_UPLOAD_IMG);
	}

}
